import React, { useState, useEffect } from 'react'
import { Input, Button, Space } from 'antd-mobile'
import axios from 'axios'
import { useNavigate } from 'react-router-dom'
import { useDispatch } from 'react-redux'
import { SET_TAG } from '../../store/reducer'
type Props = {}

const Index = (props: Props) => {
	const [value, setValue] = useState('')
	const [count, setCount] = useState(5)
	const [code, setCode] = useState('')
	const navigate = useNavigate()
	const dispatch = useDispatch()
	const onSubmit = () => {
		setCount(count - 1)
		axios.post('/tel/code', { tel: value }).then(resp => {
			const { code, telCode } = resp.data
			if (code === 200) {
				setCode(telCode)
			} else {

			}
		})
	}

	const onLogin = () => {
		axios.post('/login', { tel: value, code }).then(resp => {
			const { code, data, token } = resp.data
			if(code === 200) {
				const { tel, tag } = data;
				dispatch({ type: SET_TAG, payload: tag })
				navigate('/')
				localStorage.setItem('token', token)
				localStorage.setItem('tag', JSON.stringify(tag))
			} 
		

		})
	}
	useEffect(() => {
		if (count === 5) {

		} else if (count <= 0) {
			setCount(5)
		} else {
			setTimeout(() => {
				setCount(count - 1)
			}, 1000)
		}
	}, [count])

	return (
		<div>
			<h1>登录</h1>
			<Input placeholder='请输入手机号'
				clearable
				value={value}
				onChange={val => {
					setValue(val)
				}} />
			<Input placeholder='请输入验证码'
				clearable
				value={code}
				onChange={val => {
					setCode(val)
				}} />

			{count}
			<Button
				block
				color='primary'
				disabled={count !== 5}
				onClick={() => onSubmit()}>{count === 5 ? '获取验证码' : `倒计时还有` + count + `s`}</Button>
			<Button onClick={() => onLogin()} block
				color='primary' style={{ marginTop: '10px' }}>登录</Button>
		</div>
	)
}

export default Index